<template>
  <div class="search-page hiddenScroll">
    <LayoutContainer>
      <div class="search">
        <Search v-if="searchValue" @search="handleSearch" :search="searchValue"></Search>
      </div>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
      >
        <el-menu-item index="1">商城</el-menu-item>
        <el-menu-item index="2">论坛</el-menu-item>
      </el-menu>
      <div class="main">
        <div class="shop" v-if="activeIndex === '1'">
          <GoodsItem v-if="goodsList.length > 0" v-for="item in goodsList" :obj="item"></GoodsItem>
          <el-empty v-else description="没有相关的商品" />
        </div>
        <div class="forum" v-else>
          <Waterfall
            v-if="forumList.length !== 0"
            style="height: 1200px"
            :list="forumList"
            :breakpoints="breakpoints"
            backgroundColor="#f5faf6"
          >
            <template #default="{ item, url, index }">
              <div class="card-container" v-if="forumList">
                <Card :obj="item" />
              </div>
            </template>
          </Waterfall>
          <el-empty v-else description="没有相关的记录" />
        </div>
      </div>
    </LayoutContainer>
  </div>
</template>

<script setup>
import LayoutContainer from '@/layout/LayoutContainer.vue'
import Search from '@/components/Search.vue'
import GoodsItem from '../Shop/components/GoodsItem.vue'
import { Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import { ref } from 'vue'
import { searchGood } from '@/api/shop'
import { startLoading, stopLoading } from '@/utils/loading'
import { searchPost } from '@/api/forum'
import Card from '../Forum/components/Card.vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const searchValue = ref('')

const breakpoints = {
  9999: { rowPerView: 4 },
  1200: { rowPerView: 3 },
  800: { rowPerView: 2 },
  500: { rowPerView: 1 },
}

const activeIndex = ref('1')

const handleSelect = (value) => {
  activeIndex.value = value
}

onMounted(() => {
  searchValue.value = route.params.searchQuery || ''
  handleSearch()
})

const goodsList = ref([])

const forumList = ref([])

const handleSearch = async (word) => {
  if (!word) {
    word = searchValue.value
  }
  startLoading()

  // 获取搜索商品
  const { data } = (await searchGood(word)).data
  goodsList.value = data

  // 获取帖子
  const res = (await searchPost(word)).data
  forumList.value = res.data

  stopLoading()
}
</script>

<style scoped less="scss">
.search-page {
  .search {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: start;
  }

  .main {
    min-height: 600px;
  }

  .el-menu--horizontal {
    --el-menu-horizontal-height: 40px;
  }
}
</style>
